let tmpUserId = Math.random() * 1000 + 1;
var MySocket = {
    url: 'http://localhost:9092',
    currSocketIO: false,
    userInfo: {
        userId: tmpUserId,
        userName: 'user-' + tmpUserId,
        token: ''
    }
}

// 显示消息
MySocket.appendMessage = function (message) {
    var currentTime = "<span class='time'>" + MySocket.formatTime(new Date()) + "</span>";
    var element = $("<div class='message-row'>" + currentTime + " " + message + "</div>");
    $('#console').prepend(element);
}

// 初始化
MySocket.init = function () {
    // 创建通道连接
    MySocket.currSocketIO = io.connect(MySocket.url + '?userId=' + MySocket.userId);
    MySocket.currSocketIO.on('connect', function () {
        MySocket.appendMessage('<span class="connect-msg">socket服务端(' + MySocket.url + ')-连接成功!</span>');
    });
    MySocket.currSocketIO.on('newSocketIO-ServerMessage', function (newMessage) {
        if (newMessage.eventType==='LOGIN'){
            if (newMessage.message!=='ERROR'){
                var loginUser = JSON.parse(newMessage.message);
                MySocket.appendMessage('<span class="username-msg">登录成功: 用户名(' + loginUser.username + '),用户ID:('+loginUser.userId+')</span> ');
            }else{
                MySocket.appendMessage('<span class="username-msg">登录失败!</span> ');
            }
        }

        if (newMessage.eventType==='NORMAL'){
            MySocket.appendMessage('<span class="username-msg">新消息(来自用户' + newMessage.fromUserKey + '):('+newMessage.message+')</span> ');
        }

    });
    MySocket.currSocketIO.on('disconnect', function () {
        MySocket.appendMessage('<span class="disconnect-msg">socket服务端(' + MySocket.url + ')-断开链接!</span>');
    });

    // 监听回车键
    $(document).keydown(function (e) {
        if (e.keyCode === 13) {
            MySocket.sendMessage({
                message: $('#messageInput').val()
            })
        }
    });

    // 登录
    $('#loginButton').on('click', function () {
        // Bearer eyJhbGciOiJIUzI1NiJ9.eyJ0b2tlbklkIjoiY2Q5ZTZkNDgtNGI1Zi00YzQ1LWJjZjAtZTQ5MjkzYjNlOTVlIiwiaWQiOiJXWkc4UzEzUG41UUxVOUNrOTJmTTNRPT0iLCJ1c2VyVHlwZSI6Ik1lbWJlciIsInVzZXJuYW1lIjoiMTUyMDAwMDAwMjAiLCJpYXQiOjE2NjE2NjU5NzYsImV4cCI6MTY2MTc1MjM3Nn0.we7XfJ7DjtydzdiW8AIgt7uBJxLfWval6M6-AAxwzQQ
        var token = $('#token').val();
        if (!token) {
            return alert('token不能为空')
        }
        MySocket.userInfo.token=token

        $('#loginButton').attr('title','token: '+token)
        // 发送-登录消息
        MySocket.sendMessage({
            eventType: 'LOGIN',
            token: MySocket.userInfo.token
        })
    })

    // 发送消息
    $('#sendMessageButton').on('click', function () {
        MySocket.sendMessage({
            message: $('#messageInput').val()
        })
    })

    // 断开链接
    $('#disConnectButton').on('click', function () {
        MySocket.sendDisconnect()
    })
}

// 发送消息
MySocket.sendMessage = function (messageParams) {
    if (messageParams.message === '') {
        return alert('发送消息 不能为空')
    }
    var toUserKey=''
    if ($('#sendToUserId').val()){
        toUserKey=$('#sendToUserType').val()+'_'+$('#sendToUserId').val()
    }
    var messageObj = {
        messageType: 'text',
        message: '',
        token:MySocket.userInfo.token?MySocket.userInfo.token:'',
        userType: $('#userType').val(),
        userId:0,
        deviceId: $('#deviceId').val(),
        eventType: 'NORMAL',
        fromUserKey:'',
        toUserKey: toUserKey,
    };
    // 发往后端 @OnEvent("newSocketIO-ClientMessage")注解的方法
    MySocket.currSocketIO.emit('newSocketIO-ClientMessage', Object.assign(messageObj, messageParams));
    $('#messageInput').val('');
}

// 关闭通道连接 可被@OnDisconnect注解的方法监听
MySocket.sendDisconnect = function () {
    MySocket.currSocketIO.disconnect();
}

// 格式化时间
MySocket.formatTime = function (dat) {
    //获取年月日，时间
    var year = dat.getFullYear();
    var mon = (dat.getMonth() + 1) < 10 ? "0" + (dat.getMonth() + 1) : dat.getMonth() + 1;
    var data = dat.getDate() < 10 ? "0" + (dat.getDate()) : dat.getDate();
    var hour = dat.getHours() < 10 ? "0" + (dat.getHours()) : dat.getHours();
    var min = dat.getMinutes() < 10 ? "0" + (dat.getMinutes()) : dat.getMinutes();
    var seon = dat.getSeconds() < 10 ? "0" + (dat.getSeconds()) : dat.getSeconds();
    var newDate = year + "-" + mon + "-" + data + " " + hour + ":" + min + ":" + seon;
    return newDate;
}

$(function(){
    MySocket.init()
})
